package com.wl.mr.sequence;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;

public class SequenceRecordReader extends RecordReader<Text, BytesWritable> {

    private FileSplit split;
    Configuration conf =new Configuration();

    private Text key = new Text();
    private BytesWritable value = new BytesWritable();

    @Override
    public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
        this.split = (FileSplit) split;
        this.conf = context.getConfiguration();
    }

    private Boolean flag = true;
    @Override
    public boolean nextKeyValue() throws IOException, InterruptedException {

        if(flag){
            byte[] context = new byte[(int) split.getLength()];
            FileSystem fileSystem = null;
            FSDataInputStream open = null;

            Path path = split.getPath();
            fileSystem = path.getFileSystem(conf);

            open = fileSystem.open(path);

            IOUtils.readFully(open,context,0,context.length);

            key.set(path.toString());
            value.set(context, 0, context.length);

            IOUtils.closeStream(open);

            flag = false;
            return true;
        }

        return false;
    }

    @Override
    public Text getCurrentKey() throws IOException, InterruptedException {
        return key;
    }

    @Override
    public BytesWritable getCurrentValue() throws IOException, InterruptedException {
        return value;
    }

    @Override
    public float getProgress() throws IOException, InterruptedException {
        return 0;
    }

    @Override
    public void close() throws IOException {

    }
}
